<template>
  <div class="prescription-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">处方流转订单管理</h1>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="section-header">
        <el-icon class="section-icon">
          <Grid />
        </el-icon>
        <span class="section-title">筛选</span>
      </div>

      <div class="filter-content">
        <div class="filter-row">
          <el-input
            v-model="filterForm.searchText"
            placeholder="输入患者姓名或手机号"
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <div class="date-filters">
            <span class="date-label">日期</span>
            <el-date-picker
              v-model="filterForm.startDate"
              type="datetime"
              placeholder="开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="date-picker"
            />
            <el-date-picker
              v-model="filterForm.endDate"
              type="datetime"
              placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="date-picker"
            />
          </div>

          <el-button type="primary" @click="handleFilter" class="filter-btn">
            筛选
          </el-button>
        </div>
      </div>
    </div>

    <!-- 数据列表区域 -->
    <div class="data-section">
      <div class="section-header">
        <el-icon class="section-icon">
          <List />
        </el-icon>
        <span class="section-title">数据列表</span>
      </div>

      <!-- 状态标签页 -->
      <div class="status-tabs">
        <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
          <el-tab-pane label="全部" name="all" />
          <el-tab-pane label="待支付" name="pending" />
          <el-tab-pane label="已完成" name="completed" />
          <el-tab-pane label="已失效" name="invalid" />
        </el-tabs>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无数据"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" label="选择" />
          <el-table-column prop="orderNo" label="订单编号" width="150" />
          <el-table-column prop="prescriptionNo" label="处方编号" width="150" />
          <el-table-column prop="patientName" label="患者" width="120" />
          <el-table-column prop="departmentName" label="科室" width="120" />
          <el-table-column prop="doctor" label="医生" width="120" />
          <el-table-column prop="cost" label="费用" width="100">
            <template #default="scope">
              <span class="amount">¥{{ scope.row.cost?.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" width="120">
            <template #default="scope">
              <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
                {{
                  scope.row.orderStatusName ||
                  getOrderStatusText(scope.row.orderStatus)
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="prescriptionStatus"
            label="处方单状态"
            width="120"
          >
            <template #default="scope">
              <el-tag
                :type="getPrescriptionStatusType(scope.row.prescriptionStatus)"
              >
                {{
                  scope.row.prescriptionStatusName ||
                  getPrescriptionStatusText(scope.row.prescriptionStatus)
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="purchaseMethod" label="购药方式" width="100">
            <template #default="scope">
              <span>{{
                scope.row.purchaseMethodName ||
                getPurchaseMethodText(scope.row.purchaseMethod)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="dispensingStatus" label="发药状态" width="100">
            <template #default="scope">
              <el-tag
                :type="getDispensingStatusType(scope.row.dispensingStatus)"
              >
                {{
                  scope.row.dispensingStatusName ||
                  getDispensingStatusText(scope.row.dispensingStatus)
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="handleView(scope.row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Grid, List, Search } from "@element-plus/icons-vue";
import { OrderAPI } from "../api/order";

const router = useRouter();

// 响应式数据
const loading = ref(false);
const activeStatus = ref("all");
const selectedRows = ref<any[]>([]);

// 筛选表单
const filterForm = reactive({
  searchText: "",
  startDate: "",
  endDate: "",
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0,
});

// 表格数据
const tableData = ref([]);

// 订单状态枚举
const OrderStatus = {
  PENDING: 0, // 待支付
  COMPLETED: 5, // 已完成
  INVALID: 10, // 已失效
};

// 处方状态枚举
const PrescriptionStatus = {
  PENDING: 0, // 待审核
  APPROVED: 5, // 已审核
  COMPLETED: 10, // 已完成
  INVALID: 15, // 已失效
};

// 购药方式枚举
const PurchaseMethod = {
  PHARMACY: 0, // 药店购药
  ONLINE: 1, // 线上购药
};

// 发药状态枚举
const DispensingStatus = {
  PENDING: 0, // 待支付
  PROCESSING: 1, // 发药中
  COMPLETED: 2, // 已发药
  CANCELLED: 3, // 已取消
};

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    [OrderStatus.PENDING]: "warning",
    [OrderStatus.COMPLETED]: "success",
    [OrderStatus.INVALID]: "info",
  };
  return statusMap[status] || "info";
};

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    [OrderStatus.PENDING]: "待支付",
    [OrderStatus.COMPLETED]: "已完成",
    [OrderStatus.INVALID]: "已失效",
  };
  return statusMap[status] || "未知";
};

// 获取处方状态类型
const getPrescriptionStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    [PrescriptionStatus.PENDING]: "warning",
    [PrescriptionStatus.APPROVED]: "primary",
    [PrescriptionStatus.COMPLETED]: "success",
    [PrescriptionStatus.INVALID]: "info",
  };
  return statusMap[status] || "info";
};

// 获取处方状态文本
const getPrescriptionStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    [PrescriptionStatus.PENDING]: "待审核",
    [PrescriptionStatus.APPROVED]: "已审核",
    [PrescriptionStatus.COMPLETED]: "已完成",
    [PrescriptionStatus.INVALID]: "已失效",
  };
  return statusMap[status] || "未知";
};

// 获取购药方式文本
const getPurchaseMethodText = (method: number) => {
  const methodMap: Record<number, string> = {
    [PurchaseMethod.PHARMACY]: "药店购药",
    [PurchaseMethod.ONLINE]: "线上购药",
  };
  return methodMap[method] || "未知";
};

// 获取发药状态类型
const getDispensingStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    [DispensingStatus.PENDING]: "warning",
    [DispensingStatus.PROCESSING]: "primary",
    [DispensingStatus.COMPLETED]: "success",
    [DispensingStatus.CANCELLED]: "info",
  };
  return statusMap[status] || "info";
};

// 获取发药状态文本
const getDispensingStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    [DispensingStatus.PENDING]: "待支付",
    [DispensingStatus.PROCESSING]: "发药中",
    [DispensingStatus.COMPLETED]: "已发药",
    [DispensingStatus.CANCELLED]: "已取消",
  };
  return statusMap[status] || "未知";
};

// 计算当前选中的订单状态值
const currentOrderStatus = computed(() => {
  switch (activeStatus.value) {
    case "pending":
      return OrderStatus.PENDING; // 0
    case "completed":
      return OrderStatus.COMPLETED; // 5
    case "invalid":
      return OrderStatus.INVALID; // 10
    default:
      return undefined; // 全部状态
  }
});

// 加载处方订单数据
const loadPrescriptionOrders = async () => {
  try {
    loading.value = true;

    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      Keyword: filterForm.searchText || undefined,
      StartTime: filterForm.startDate || undefined,
      EndTime: filterForm.endDate || undefined,
      OrderStatus: currentOrderStatus.value,
    };

    console.log("调用处方订单API，参数:", params);
    console.log("当前选中状态:", activeStatus.value);
    console.log("计算的状态值:", currentOrderStatus.value);

    const response = await OrderAPI.getPrescriptionOrdersPage(params);

    if (response && response.data) {
      tableData.value = response.data.data || [];
      pagination.total = response.data.totalCount || 0;
      console.log("处方订单数据加载成功:", response);
      console.log("加载到", tableData.value.length, "条数据");
    } else {
      console.error("API响应格式错误:", response);
      ElMessage.error("数据加载失败");
    }
  } catch (error) {
    console.error("加载处方订单数据失败:", error);
    ElMessage.error("数据加载失败，请检查网络连接");
  } finally {
    loading.value = false;
  }
};

// 处理筛选
const handleFilter = () => {
  console.log("筛选按钮点击，当前筛选条件:", {
    searchText: filterForm.searchText,
    startDate: filterForm.startDate,
    endDate: filterForm.endDate,
    activeStatus: activeStatus.value,
  });
  pagination.currentPage = 1;
  loadPrescriptionOrders();
};

// 处理状态变化
const handleStatusChange = (tab: any) => {
  console.log("状态标签切换:", tab.props.label, "状态值:", activeStatus.value);

  // 直接计算状态值，避免反应慢一步的问题
  let orderStatus: number | undefined;
  switch (tab.props.name) {
    case "pending":
      orderStatus = OrderStatus.PENDING; // 0
      break;
    case "completed":
      orderStatus = OrderStatus.COMPLETED; // 5
      break;
    case "invalid":
      orderStatus = OrderStatus.INVALID; // 10
      break;
    default:
      orderStatus = undefined; // 全部状态
  }

  console.log("直接计算的状态值:", orderStatus);

  pagination.currentPage = 1;

  // 使用nextTick确保DOM更新完成
  nextTick(() => {
    // 临时覆盖loadPrescriptionOrders中的状态值
    const tempLoadPrescriptionOrders = async () => {
      try {
        loading.value = true;

        const params = {
          PageIndex: pagination.currentPage,
          PageSize: pagination.pageSize,
          Keyword: filterForm.searchText || undefined,
          StartTime: filterForm.startDate || undefined,
          EndTime: filterForm.endDate || undefined,
          OrderStatus: orderStatus, // 使用直接计算的值
        };

        console.log("调用处方订单API，参数:", params);
        console.log("当前选中状态:", activeStatus.value);
        console.log("直接计算的状态值:", orderStatus);

        const response = await OrderAPI.getPrescriptionOrdersPage(params);

        if (response && response.data) {
          tableData.value = response.data.data || [];
          pagination.total = response.data.totalCount || 0;
          console.log("处方订单数据加载成功:", response);
          console.log("加载到", tableData.value.length, "条数据");
        } else {
          console.error("API响应格式错误:", response);
          ElMessage.error("数据加载失败");
        }
      } catch (error) {
        console.error("加载处方订单数据失败:", error);
        ElMessage.error("数据加载失败，请检查网络连接");
      } finally {
        loading.value = false;
      }
    };

    tempLoadPrescriptionOrders();
  });
};

// 处理查看
const handleView = (row: any) => {
  console.log("查看处方订单:", row.orderNo);
  router.push(`/orders/prescription-detail/${row.id}`);
};

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
  console.log("选中的行:", selectedRows.value);
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadPrescriptionOrders();
};

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadPrescriptionOrders();
};

// 组件挂载时加载数据
onMounted(() => {
  loadPrescriptionOrders();
});
</script>

<style scoped>
.prescription-order-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.page-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.page-title {
  margin: 0;
  color: #fff;
  font-size: 24px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.filter-section,
.data-section {
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.data-section {
  border-bottom: none;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
}

.section-icon {
  font-size: 20px;
  color: #409eff;
  margin-right: 8px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.filter-content {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 300px;
}

.date-filters {
  display: flex;
  align-items: center;
  gap: 12px;
}

.date-label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.date-picker {
  width: 180px;
}

.filter-btn {
  min-width: 80px;
  height: 40px;
}

.status-tabs {
  margin-bottom: 20px;
}

.status-tabs :deep(.el-tabs__header) {
  margin-bottom: 0;
}

.status-tabs :deep(.el-tabs__nav-wrap) {
  padding-bottom: 0;
}

.status-tabs :deep(.el-tabs__item) {
  font-weight: 500;
  padding: 0 24px;
}

.status-tabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

.status-tabs :deep(.el-tabs__active-bar) {
  background-color: #409eff;
  height: 3px;
}

.table-container {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-container :deep(.el-table) {
  border-radius: 8px;
}

.table-container :deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
  border-bottom: 2px solid #e9ecef;
}

.table-container :deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
}

.table-container
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafbfc;
}

.amount {
  color: #e6a23c;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    min-width: auto;
  }

  .date-filters {
    flex-direction: column;
    align-items: stretch;
  }

  .date-picker {
    width: 100%;
  }
}
</style>